package com.example.flutteruikit;

import android.text.TextUtils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



public class ParamsUtil {

	private static final String SIG = "sig";
	private static final String APP = "dish";
	private static final String SID = "1";
	private static final String V = "3";
	private static final String FORMAT = "json";
	public static final String OPER = "admin";


	/**
	 * 组织接口上传的参数
	 *
	 * @param value 不同接口 有特定的参数 放在map中 然后再次组合
	 */
	public synchronized static Map<String, String> getParams(Map<String, String> value, String key) {
		Map<String, String> params = new HashMap<>();
		params.put("v", V);
		params.put("app", APP);
		params.put("sid", SID);
		params.put("d", DateUtil.longToDate(DateUtil.nowTimeLong(), DateUtil.FORMAT_DATE));
		params.put("oper", "admin");
		params.put("format", FORMAT);
		if (value != null) {
			params.putAll(value);
		}

		List<String> paramList = new ArrayList<>();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			paramList.add(entry.getKey() + "=" + entry.getValue());
		}

		String paramsStr[] = new String[paramList.size()];
		for (int j = 0; j < paramList.size(); j++) {
			paramsStr[j] = paramList.get(j);
		}

		StringBuilder result = new StringBuilder();
		Arrays.sort(paramsStr, String.CASE_INSENSITIVE_ORDER);
		for (String s : paramsStr) {
			result.append(s);
		}


		result.append(key);


		params.put(SIG, md5Str(result.toString()));
		return params;
	}

	/**
	 * md5加密方法
	 */
	public static String md5Str(String params) {
		MessageDigest messageDigest;
		BigInteger bigInteger = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			bigInteger = new BigInteger(1, messageDigest.digest(params.getBytes("utf-8")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return String.format("%032x", bigInteger);
	}
}
